/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.client.messaging.inbox;

import java.awt.BorderLayout;
import java.util.logging.Logger;
import nl.cloudfarming.client.messaging.Message;
import nl.cloudfarming.client.messaging.MessageModule;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.openide.util.Lookup;
import org.netbeans.api.settings.ConvertAsProperties;

/**
 * Top component which displays the Message Inbox.
 */
@ConvertAsProperties(dtd = "-//nl.cloudfarming.client.messaging//MessageInbox//EN",
autostore = false)
public final class MessageInboxTopComponent extends TopComponent implements PropertyChangeListener {

    private static MessageInboxTopComponent instance;
    private static final String PREFERRED_ID = "MessageInboxTopComponent";
    private MessageInboxPanel messageInboxPanel;
    //Use getMesageInbox() to get reference
    private MessageInbox messageInbox;
    private final String MESSAGE_INBOX_TITLE = NbBundle.getMessage(MessageModule.class, "CTL_MessageInboxTopComponent");
    private final String TOOLTIP_TEXT = NbBundle.getMessage(MessageModule.class, "HINT_MessageInboxTopComponent");

    public MessageInboxTopComponent() {
        messageInbox = Lookup.getDefault().lookup(MessageInbox.class);
        assert messageInbox != null;
        associateLookup(messageInbox.getLookup());

        initComponents();
    }

    public void addMessage(Message message) {
        messageInboxPanel.addMessage(message);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     */
    private void initComponents() {

        this.setLayout(new BorderLayout());
        messageInboxPanel = new MessageInboxPanel();
        this.add(messageInboxPanel);

        this.setName(MESSAGE_INBOX_TITLE);
        this.setToolTipText(TOOLTIP_TEXT);

        for (Message mesage : messageInbox.getMessages()) {
            this.addMessage(mesage);
        }
        
        messageInbox.addMessagePropertyChangeListener(this);

    }

    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized MessageInboxTopComponent getDefault() {
        if (instance == null) {
            instance = new MessageInboxTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the MessageInboxTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized MessageInboxTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(MessageInboxTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof MessageInboxTopComponent) {
            return (MessageInboxTopComponent) win;
        }
        Logger.getLogger(MessageInboxTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();

    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
    }

    Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    /**
     * Updates the listers That a property of the inbox has changed
     * @param evt 
     */
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (evt.getNewValue() instanceof Message) {
            this.addMessage((Message) evt.getNewValue());
        }

    }
}
